package com.wxl.multi.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyService {

    @Resource(name="cluster1RedisTemplate")
    private RedisTemplate<String, String> cluster1RedisTemplate;

    @Resource(name="cluster2RedisTemplate")
    private RedisTemplate<String, String> cluster2RedisTemplate;

    // 使用 cluster1RedisTemplate 或 cluster2RedisTemplate 来执行操作...

    /**
     * 使用 Pipeline 机制批量获取键值。
     *
     * @param keys 要查询的键列表
     * @param template 指定要使用的 RedisTemplate 实例
     * @return 查询结果列表
     */
    public List<String> batchGet(List<String> keys, RedisTemplate<String, String> template) {
        return template.executePipelined((RedisCallback<String>) connection -> {
            for (String key : keys) {
                connection.get(key.getBytes());
            }
            return null;
        }).stream()
                .map(reply -> reply == null ? null : reply.toString())
                .collect(Collectors.toList());
    }

    // 示例：使用 cluster1RedisTemplate 进行批量查询
    public void exampleBatchGetFromCluster1() {
        List<String> keys = Arrays.asList("wxl", "c", "d","a", "b");
        List<String> results = batchGet(keys, cluster1RedisTemplate);
        System.out.println("Results from Cluster1: " + results);
    }

    // 示例：使用 cluster2RedisTemplate 进行批量查询
    public void exampleBatchGetFromCluster2() {
        List<String> keys = Arrays.asList("wxl", "c", "d","a", "b");
        List<String> results = batchGet(keys, cluster2RedisTemplate);
        System.out.println("Results from Cluster2: " + results);
    }
}